const express = require('express');
const router = express.Router();
const { generateSudokuPuzzle } = require('../utils/sudoku');

// 创建对战房间
router.post('/create', async (req, res) => {
  try {
    const { difficulty = 'medium' } = req.body;
    
    // 验证难度参数
    const validDifficulties = ['easy', 'medium', 'hard', 'expert'];
    if (!validDifficulties.includes(difficulty)) {
      return res.status(400).json({ error: '无效的难度等级' });
    }
    
    const db = req.app.locals.db;
    
    // 生成数独题目
    const puzzle = generateSudokuPuzzle(difficulty);
    
    // 创建对战记录
    const [result] = await db.execute(
      'INSERT INTO battles (puzzle, solution, difficulty, status, created_at) VALUES (?, ?, ?, ?, NOW())',
      [JSON.stringify(puzzle.puzzle), JSON.stringify(puzzle.solution), difficulty, 'waiting']
    );
    
    const battleId = result.insertId;
    
    res.json({
      success: true,
      data: {
        battleId,
        puzzle: puzzle.puzzle,
        difficulty,
        status: 'waiting',
        message: '对战房间创建成功'
      }
    });
  } catch (error) {
    console.error('创建对战房间失败:', error);
    res.status(500).json({ error: '创建对战房间失败' });
  }
});

// 加入对战房间
router.post('/join/:battleId', async (req, res) => {
  try {
    const { battleId } = req.params;
    
    const db = req.app.locals.db;
    
    // 检查对战房间是否存在且可加入
    const [battles] = await db.execute(
      'SELECT * FROM battles WHERE id = ? AND status = ?',
      [battleId, 'waiting']
    );
    
    if (battles.length === 0) {
      return res.status(404).json({ error: '对战房间不存在或已开始' });
    }
    
    const battle = battles[0];
    
    // 更新对战状态为进行中
    await db.execute(
      'UPDATE battles SET status = ?, started_at = NOW() WHERE id = ?',
      ['playing', battleId]
    );
    
    res.json({
      success: true,
      data: {
        battleId,
        puzzle: JSON.parse(battle.puzzle),
        difficulty: battle.difficulty,
        status: 'playing',
        message: '成功加入对战房间'
      }
    });
  } catch (error) {
    console.error('加入对战房间失败:', error);
    res.status(500).json({ error: '加入对战房间失败' });
  }
});

// 获取对战房间信息
router.get('/:battleId', async (req, res) => {
  try {
    const { battleId } = req.params;
    
    const db = req.app.locals.db;
    
    const [battles] = await db.execute(
      'SELECT * FROM battles WHERE id = ?',
      [battleId]
    );
    
    if (battles.length === 0) {
      return res.status(404).json({ error: '对战房间不存在' });
    }
    
    const battle = battles[0];
    
    res.json({
      success: true,
      data: {
        battleId: battle.id,
        puzzle: JSON.parse(battle.puzzle),
        difficulty: battle.difficulty,
        status: battle.status,
        winner: battle.winner_id,
        createdAt: battle.created_at,
        startedAt: battle.started_at,
        finishedAt: battle.finished_at
      }
    });
  } catch (error) {
    console.error('获取对战房间信息失败:', error);
    res.status(500).json({ error: '获取对战房间信息失败' });
  }
});

// 完成对战
router.post('/:battleId/complete', async (req, res) => {
  try {
    const { battleId } = req.params;
    const { playerId, score, time } = req.body;
    
    if (!playerId || score === undefined || time === undefined) {
      return res.status(400).json({ error: '缺少必需参数' });
    }
    
    const db = req.app.locals.db;
    
    // 检查对战是否存在且正在进行
    const [battles] = await db.execute(
      'SELECT * FROM battles WHERE id = ? AND status = ?',
      [battleId, 'playing']
    );
    
    if (battles.length === 0) {
      return res.status(404).json({ error: '对战不存在或已结束' });
    }
    
    // 更新对战结果
    await db.execute(
      'UPDATE battles SET winner_id = ?, winner_score = ?, winner_time = ?, status = ?, finished_at = NOW() WHERE id = ?',
      [playerId, score, time, 'finished', battleId]
    );
    
    // 保存对战结果到游戏记录
    const battle = battles[0];
    await db.execute(
      'INSERT INTO games (puzzle, solution, difficulty, score, time_spent, completed, battle_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())',
      [battle.puzzle, battle.solution, battle.difficulty, score, time, 1, battleId]
    );
    
    res.json({
      success: true,
      data: {
        battleId,
        winner: playerId,
        score,
        time,
        message: '对战完成'
      }
    });
  } catch (error) {
    console.error('完成对战失败:', error);
    res.status(500).json({ error: '完成对战失败' });
  }
});

// 获取对战历史
router.get('/history/list', async (req, res) => {
  try {
    const { page = 1, limit = 10, status } = req.query;
    const offset = (page - 1) * limit;
    
    const db = req.app.locals.db;
    
    let query = 'SELECT * FROM battles';
    let params = [];
    
    if (status) {
      query += ' WHERE status = ?';
      params.push(status);
    }
    
    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), parseInt(offset));
    
    const [battles] = await db.execute(query, params);
    
    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM battles';
    let countParams = [];
    
    if (status) {
      countQuery += ' WHERE status = ?';
      countParams.push(status);
    }
    
    const [countResult] = await db.execute(countQuery, countParams);
    const total = countResult[0].total;
    
    // 处理数据，解析JSON字段
    const processedBattles = battles.map(battle => ({
      ...battle,
      puzzle: JSON.parse(battle.puzzle),
      solution: JSON.parse(battle.solution)
    }));
    
    res.json({
      success: true,
      data: {
        battles: processedBattles,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total,
          pages: Math.ceil(total / limit)
        }
      }
    });
  } catch (error) {
    console.error('获取对战历史失败:', error);
    res.status(500).json({ error: '获取对战历史失败' });
  }
});

// 获取等待中的对战房间
router.get('/waiting/list', async (req, res) => {
  try {
    const { difficulty, limit = 10 } = req.query;
    
    const db = req.app.locals.db;
    
    let query = 'SELECT id, difficulty, created_at FROM battles WHERE status = ?';
    let params = ['waiting'];
    
    if (difficulty) {
      query += ' AND difficulty = ?';
      params.push(difficulty);
    }
    
    query += ' ORDER BY created_at ASC LIMIT ?';
    params.push(parseInt(limit));
    
    const [battles] = await db.execute(query, params);
    
    res.json({
      success: true,
      data: {
        battles
      }
    });
  } catch (error) {
    console.error('获取等待中的对战房间失败:', error);
    res.status(500).json({ error: '获取等待中的对战房间失败' });
  }
});

module.exports = router;